package com.hrt.datasender.web.strategy;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.springframework.stereotype.Service;

import com.hrt.datasender.datadao.model.BcSendPlatformDataStrategyModel;
import com.hrt.datasender.datadao.service.BcSendPlatformDataStrategyService;
import com.hrt.datasender.datastorage.strategy.IStorageStrategy;
import com.hrt.datasender.datastorage.strategy.StrategyLoader;

@Service
public final class StrategyService {

    private static volatile StrategyService instance;

    private StrategyService() {

    }

    public static StrategyService getInstance() {
        if (instance == null) {
            synchronized (StrategyService.class) {
                if (instance == null) {
                    instance = new StrategyService();
                }
            }
        }
        return instance;
    }

    /**
     * 获取系统中所有存在的监控数据策略
     * 
     * @return
     * @throws IOException
     * @throws IllegalAccessException
     * @throws InstantiationException
     * @throws ClassNotFoundException
     */
    public List<StrategyModel> getExistMonitorDataStrategy()
            throws ClassNotFoundException, InstantiationException, IllegalAccessException, IOException {

        List<IStorageStrategy> strategys = StrategyLoader.getInstance().getExistStrategy();
        List<StrategyModel> strategyModels = new ArrayList<>();

        for (IStorageStrategy strategy : strategys) {

            StrategyModel model = new StrategyModel();
            model.setStrategyId(strategy.getStrategyId());
            model.setStrategyName(strategy.getShowName());

            strategyModels.add(model);
        }

        return strategyModels;
    }

    public List<StrategyModel> getListByPlatform(String platformId)
            throws ClassNotFoundException, InstantiationException, IllegalAccessException, IOException {

        List<BcSendPlatformDataStrategyModel> platformStrategys = BcSendPlatformDataStrategyService.getInstance()
                .getList(platformId);

        List<StrategyModel> strategyModels = new ArrayList<>();

        for (BcSendPlatformDataStrategyModel platformStrategy : platformStrategys) {

            String strategyId = platformStrategy.getStorageStrategyId();
            IStorageStrategy strategy = StrategyLoader.getInstance().getStrategyById(strategyId);

            if (strategy != null) {
                StrategyModel model = new StrategyModel();
                model.setStrategyId(strategy.getStrategyId());
                model.setStrategyName(strategy.getShowName());
                model.setDataType(strategy.getDataType());
                model.setDataInterval(strategy.getDataInterval());
                model.setStrategyTable(strategy.getStoageTable());
                strategyModels.add(model);
            }
        }

        return strategyModels;
    }

}
